import axios from 'axios';
import {
    Message
} from 'element-ui';
import router from '@/router/index.js';
let pathRewrite = '/api';
export default{
    download(data){
        return pathRewrite + data.url + (sessionStorage.getItem("tokenId") ? `?tokenId=${sessionStorage.getItem("tokenId")}` : '')
    },
    service(data, type) {
        let headers = {};
        if (type) {
            switch (type) {
                case 'upload':
                    headers = {
                        'deviceCode': 'A95ZEF1-47B5-AC90BF3'
                    }
                    break;
            }
        } else {
            headers = {
                'X-Requested-With': 'XMLHttpRequest',
                'Content-Type': 'application/json;charset=UTF-8'
            }
        };
        const service = axios.create({
            timeout: 50000,
            headers
        });
        /*
         *增加请求拦截器
         */
        service.interceptors.request.use((config) => {
            //预处理请求的信息
            if (config.method === 'post') {
                config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
            }
            if (process.env.NODE_ENV === 'development') {
                config.url = pathRewrite + config.url;
            }
            config.url = config.url + (sessionStorage.getItem("tokenId") ? `?tokenId=${sessionStorage.getItem("tokenId")}` : '');
            return config
        }, (error) => {
            //预处理请求有异常error时抛出错误
            return Promise.reject(error)
        });
        /*
         *增加响应拦截器
         */
        service.interceptors.response.use((response) => {
            if (response.status === 200) {
                if (type == 'upload'){
                    return response.data
                }
                if (response.data.statusCode === "200") {
                    return response.data
                } else {

                    Message.error(response.data.desc);
                    return Promise.reject(response.data);
                }
            } else {
                return Promise.reject(response.status)
            }
        }, error => {
            if (error.response) {
                switch (error.response.status) {
                    case 401:
                        router.replace({
                            path: '/login',
                            query: {
                                redirect: router.history.current.fullPath
                            }
                        })
                        break;
                    case 504:
                    case 404:
                        Message.error('接口出错');
                        break;
                    default:
                        Message.error('加载失败！ 请重新加载...');
                        break;
                }
            }
            return Promise.reject(error)
        })
        return service(data);
    }
}
